import 'dart:convert';

import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/provider/user.dart';
import 'package:star_author/utils/websocket_manage/websocket_manage.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';

class WebSocketHandle {
  static void socketNotificationSubscribe(BuildContext context, Map map) {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    Map user = userProvider.user ?? {};
    if (map.isEmpty) return;
    if (!((map['message'] ?? {}) is Map)) return;

    Map message = map['message'] ?? {};

    Map value = {
      ...user,
      ...{
        'summary': {
          'unread_notifications_count': message['unread_count'] ?? 0,
          ...user['summary'] ?? {},
        }
      }
    };
    userProvider.set(key: 'userInfo', value: value);
  }

  //直播间
  static void subscribeLiveChannel() {
    String subscribeStr = jsonEncode({
      "command": "subscribe",
      "identifier":
          jsonEncode({"channel": "StudioChannel", "id": StreamConf.liveId})
    });

    WebSocketManage().flexibleSubscribeLMap['StudioChannel'] = subscribeStr;

    WebSocketManage().sendMessage(subscribeStr);
  }

  static void unSubscribeLiveChannel() {
    WebSocketManage().flexibleSubscribeLMap.remove('StudioChannel');

    WebSocketManage().sendMessage(jsonEncode({
      "command": "unsubscribe",
      "identifier":
          jsonEncode({"channel": "StudioChannel", "id": StreamConf.liveId})
    }));
  }
}
